<template>
  <h1>简易购物车案例</h1>
  <table border="1" width='800px'>
    <thead>
      <tr>
        <th>名称</th>
        <th>数量 </th>
        <th>价格</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(item,index) in shop" :key="index">
        <td>{{item.name}}</td>
        <td> <button @click="jiannum(item)">-</button> {{item.num}} <button @click="addnum(item)">+</button></td>
        <td>{{item.price * item.num}}</td>
        <td><button class="del" @click="del(index)">删除商品</button></td>
      </tr>
    </tbody>
    <tfoot>
      <tr>
        <td></td>
        <td></td>
        <td></td>
        <td>总计{{total}}</td>
      </tr>
    </tfoot>
  </table>
</template>

<script setup lang='ts'>
import { ref, reactive, computed } from 'vue'
type Shop = {
  name: string,
  num: number,
  price: number
}
let total = ref(0)
const shop = reactive<Shop[]>([
  { name: '衣服', num: 1, price: 100 },
  { name: '裤子', num: 1, price: 200 },
  { name: '鞋子', num: 1, price: 300 },
])
const addnum = (item: Shop) => {
  if (item.num >= 0)
    item.num++
}
const jiannum = (item: Shop) => {
  if (item.num <= 99 && item.num > 0)
    item.num--
}
const del = (index: number) => {
  shop.splice(index, 1)
}
total = computed<number>(() => {
  return shop.reduce((prev, next) => {
    return prev + next.num * next.price
  }, 0)
})
</script>

<style scoped>
td {
  text-align: center
}

button {
  margin: 0px 20px;
}

.del {
  background-color: red;
  color: #fff;
}

.del:hover {
  background-color: crimson;
  color: #ccc;
}
</style>
